<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="计划编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入计划编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收货人" prop="custom">
        <el-input
          v-model="queryParams.custom"
          placeholder="请输入收货人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系方式" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系方式"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sales:code:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['sales:code:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sales:code:remove']"
          >删除</el-button
        >
      </el-col>
      <!-- 批量启用 -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-bell"
          size="mini"
          :disabled="multiple"
          @click="handleStatus(true)"
          v-hasPermi="['sales:code:edit']"
          >批量启用</el-button
        >
      </el-col>
      <!-- 批量禁用 -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-close-notification"
          size="mini"
          :disabled="multiple"
          @click="handleStatus(false)"
          v-hasPermi="['sales:code:edit']"
          >批量禁用</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sales:code:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="codeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="计划编码表id" align="center" prop="codeId" /> -->
      <el-table-column label="计划编码" align="center" prop="code" />
      <el-table-column label="收货人" align="center" prop="custom" />
      <el-table-column label="收货地址" align="center" prop="address" />
      <el-table-column label="联系方式" align="center" prop="phone" />
      <el-table-column label="状态" align="center" prop="status">
        <!-- <template slot-scope="scope">
        {{ statusMap[scope.row.status] }}
      </template> -->
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
        <!-- <template slot-scope="scope">
          <dict-tag
            :options="dict.type.zc_plan_code"
            :value="scope.row.status"
          />
        </template> -->
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sales:code:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sales:code:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改计划编码对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="收货人" prop="custom">
          <el-input v-model="form.custom" placeholder="请输入收货人" />
        </el-form-item>
        <el-form-item label="收货地址" prop="address" :label-width="formLabelWidth" v-model="form.address">
          <el-col :span="12">
            <el-cascader
              style="width: 100%"
              clearable
              size="large"
              :options="regionDatas"
              ref="cascaderAddr"
              :props="cateProps"
              v-model="form.address1"
              @change="handleChange"
            ></el-cascader>
          </el-col>
          <el-col :span="12">
            <el-input
              v-model="form.address2"
              placeholder="请输入详细地址"
              clearable
              maxlength="20"
              show-word-limit
            ></el-input>
          </el-col>
        </el-form-item>
        <!-- <el-form-item label="收货地址" prop="address">
          <el-input
            v-model="form.address"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item> -->
        <el-form-item label="联系方式" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系方式" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <!-- <el-option
              v-for="item in statusOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option> -->
            <el-option
              v-for="dict in dict.type.zc_plan_code"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCode,
  getCode,
  delCode,
  addCode,
  updateCode,
  changeUserStatus,
} from "@/api/sales/code";
import {
  provinceAndCityData,
  regionData,
  provinceAndCityDataPlus,
  regionDataPlus,
  codeToText,
  TextToCode,
} from "element-china-area-data";

export default {
  name: "Code",
  dicts: ["zc_plan_code"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 计划编码表格数据
      codeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: null,
        custom: null,
        address: null,
        phone: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        custom: [
          { required: true, message: "收货人不能为空", trigger: "blur" },
        ],
        address1: [
          { required: true, message: "收货地址不能为空", trigger: "blur" },
        ],
        address2: [
          { required: true, message: "详细地址不能为空", trigger: "blur" },
        ],
        // address: [
        //   { required: true, message: "收货地址不能为空", trigger: "blur" },
        // ],
        phone: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
      },
      addtions: [],
      tableData: [],
      regionDatas: regionData,
      cateProps: {
        value: "value",
        label: "label",
        children: "children",
      },
      formLabelWidth: "80px",
    };
  },
  // onload() {},
  //在实例创建完成后被立即同步调用
  created() {
    this.getList();
    //查询状态字典
    //  this.getDicts("zc_plan_code").then((response) => {
    //   this.statusOptions = response.data;
    //   this.statusOptions.forEach((dict) => {
    //     //转型
    //     dict.dictValue = parseInt(dict.dictValue);
    //     this.$set(this.statusMap, dict.dictValue, dict.dictLabel);
    //   });
    // });
  },
  methods: {
    //级联选择器详细数据
    handleChange(value) {
      console.log(value);
      this.form.address1 = value;
      var name = "";
      this.form.address1.map((item) => (name += codeToText[item] + "")); //将省市区三个拼接一起
      console.log(this.form.address1);
      this.addtions.names = name;
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "禁用";
      this.$modal
        .confirm('确认要"' + text + '"该计划编码吗？')
        .then(function () {
          return changeUserStatus(row.codeId, row.status);
        })
        .then(() => {
          this.$modal.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    /** 查询计划编码列表 */
    getList() {
      this.loading = true;
      listCode(this.queryParams).then((response) => {
        this.codeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        codeId: null,
        code: null,
        custom: null,
        address: null,
        address1: [],
        address2: "",
        phone: null,
        status: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        del: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.codeId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加计划编码";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const codeId = row.codeId || this.ids;
      getCode(codeId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改计划编码";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.codeId != null) {
            this.codeList.push(this.form); //将新增数据push到dataList数组中
            this.codeList.forEach((element) => {
              element.address = this.addtions.names + this.form.address2; // 将级联选择器的地址和input里的详细地址合并赋值给table数据表中
            });
            updateCode(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.codeList.push(this.form); //将新增数据push到dataList数组中
            this.codeList.forEach((element) => {
              element.address = this.addtions.names + this.form.address2; // 将级联选择器的地址和input里的详细地址合并赋值给table数据表中
            });
            addCode(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const codeIds = row.codeId || this.ids;
      this.$modal
        .confirm('是否确认删除编号为"' + codeIds + '"的数据项？')
        .then(function () {
          return delCode(codeIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 批量启用按钮操作
    handleStatus(value) {
      // 在方法内的this调用的方法本身 所以要改this指向
      if (value) {
        this.title = "启用";
      } else if (value === false) {
        this.title = "禁用";
      }

      var self = this;
      if (this.ids.length <= 0) {
        this.$modal.msgError("请选择需要" + this.title + "的计划编码");
        return;
      }
      this.$modal
        .confirm("是否确认" + this.title + '编号为"' + this.ids + '"的数据项？')
        .then(function () {
          self.ids.forEach((id) => {
            if (value) {
              return changeUserStatus(id, "0");
            } else if (value === false) {
              return changeUserStatus(id, "1");
            }
          });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess(this.title + "成功");
        })
        .catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "sales/code/export",
        {
          ...this.queryParams,
        },
        `code_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
